// 消息弹窗组件
import styles from '@/assets/style/message.module.less'
import Icon from '@/components/Icon'
import { getComponentRootDom } from './index'
/**
 * 弹出消息
 * @param {String} content 消息内容
 * @param {String} type 消息类型 error success info warn
 * @param {Number} duration 多久消失， 0不消失
 * @param {HTMLElement} container 容器,消息会显示到该容器的正中，如果不传，默认body
 */
export default function showMsg(options = {}) {
    const {
        content,
        type = 'info',
        duration = 2000,
        container = document.body,
        callback = () => { }
    } = options

    const div = document.createElement("div")
    div.className = `${styles.message} ${styles['message-' + type]}`
    const el = getComponentRootDom(Icon, { type })
    div.innerHTML = `<span class="${styles.icon}">${el.outerHTML}</span><span>${content}</span>`
    // 容器的position是否改动过
    if (getComputedStyle(container).position === "static" && container != document.body) {
        container.style.position = "relative";
    }
    container.appendChild(div)

    // 浏览器强行渲染
    div.clientHeight; // 导致reflow

    // 回归到正常位置
    div.style.opacity = '1';
    div.style.transform = `translate(-50%, -50%)`;

    setTimeout(() => {
        div.style.opacity = '0';
        div.style.transform = `translate(-50%, -50%) translateY(-25px)`;
        div.addEventListener("transitionend", function () {
            div.remove();
            // 运行回调函数
            callback();
        }, { once: true }
        );
    }, duration)
}

